package com.lelefly.base.daoimp;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.lelefly.base.model.Page;
import com.lelefly.base.model.Result;
import com.lelefly.base.po.LeleflyOrganization;
import com.lelefly.base.po.LeleflyOrganizationInfo;
import com.lelefly.constant.Constant;
import com.lelefly.db.dbmanager.HibernateSessionFactory;

@Repository
public class LeleflyFlyerDao extends BaseDao{

	
	public LeleflyOrganization getOrganization(String sql){
		
		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		try {
			return (LeleflyOrganization) session.createQuery(sql).uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
		return null;
	}
	
	
	public int getCount(String sql){
		
		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		try {
			BigInteger count = (BigInteger) session.createSQLQuery(sql).uniqueResult();
			return count.intValue();
//			return (int) session.createSQLQuery(sql).addScalar("count").uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}finally{
			session.close();
		}
		
	}
	
	
	public List<LeleflyOrganizationInfo> getOrganizationList(String sql){
		
		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		try {
			SQLQuery sqlQuery = session.createSQLQuery(sql);
			return sqlQuery.addScalar("organizationName").
					addScalar("flyerName")
					.addScalar("flyerPhone")
					.setResultTransformer(
					Transformers.aliasToBean(LeleflyOrganizationInfo.class))
					.list();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return null;
	}
	
	public List<LeleflyOrganization> queryOrganization(String hql,int page,int count){
		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		try {
			Query query = session.createQuery(hql);
			query.setFirstResult(page);
			query.setMaxResults(count);
			
			return query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return null;
	}
	
	public int createOrganization(String hql){
		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		try {
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return Constant.DB_STATUS_FAIL;
	}
}
